package com.kuang.controller.login;

import com.kuang.common.err.ValidationException;
import com.kuang.entity.User;
import com.kuang.service.JwtService;
import com.kuang.service.UserService;
import com.kuang.utils.pwd.MD5Util;
import com.kuang.vo.AuthResponse;
import com.kuang.vo.ResponseCode;
import com.kuang.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author 飞哥
 * @Title: 学相伴出品
 * @Description: 我们有一个学习网站：https://www.kuangstudy.com
 * @date 2021/8/3 14:31
 */
@RestController
public class LoginAuthController {
    @Autowired
    private JwtService jwtService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public AuthResponse login(String username, String password) {
        //2： 根据用户查询用户是否存在
        User user = userService.getByUserName(username);//user---GcRoots ---- userVo----redisTemplate---同一异常处理
        if (user == null) {
            throw new ValidationException(403, "用户名或密码有误!!!");
        }
        //3：对密码进行加密加盐进行处理
        password = MD5Util.md5slat(password);

        //如果用户输入的密码和数据库查询到密码不一致
        if (!password.equalsIgnoreCase(user.getPassword())) {
            throw new ValidationException(403, "用户名或密码有误!!!");
        }

        //1：todo 验证用户名和密码是否正确
        UserVo userVo = new UserVo();
        userVo.setUserid(user.getId());
        userVo.setOpenid(user.getOpenid());
        userVo.setUsername(user.getUsername());
        // token信息
        String token = jwtService.token(userVo);
        // 写入token
        userVo.setToken(token);
        // 刷新token的keyredisTemplate.opsForValue().set(userVo.getRefreshToken(), userVo, JwtService.TOKEN_EXPIRE_TI
        //ME, TimeUnit.SECONDS);
        return AuthResponse.success(userVo, ResponseCode.SUCCESS);
    }


    /**
     * 续签的方法--在有效时间内，如果你执行续签方法
     * 1: 重新生成token
     * 2：把时间的计算从当前时间开始计算
     * @param refreshToken
     * @return
     */
    @PostMapping("/refresh")
    public AuthResponse refresh(String refreshToken) {
        // 根据你刷新的key，查看当前用户是不是还在有效期内
        UserVo userVo = (UserVo) redisTemplate.opsForValue().get(refreshToken);
        if (userVo == null) {
            // 告诉用户，token已经失效，需要重新登陆
            return AuthResponse.code(ResponseCode.USER_NOT_FOUND);
        }
        // 重新生成token
        String jwt = jwtService.token(userVo);
        userVo.setToken(jwt);
        userVo.setRefreshToken(UUID.randomUUID().toString());

        redisTemplate.delete(refreshToken);
        redisTemplate.opsForValue().set(userVo.getRefreshToken(), userVo, JwtService.TOKEN_EXPIRE_TIME, TimeUnit.SECONDS);
        return AuthResponse.success(userVo, ResponseCode.SUCCESS);
    }

    @GetMapping("/logout")
    public AuthResponse logout(String refreshToken) {
        redisTemplate.delete(refreshToken);
        return AuthResponse.code(409L);
    }


    @GetMapping("/verifyusername")
    public AuthResponse verify(String username, String token) {
        return jwtService.verify(token, username);
    }


    @GetMapping("/verifyuserid")
    public AuthResponse verifyuserid(String userid, String token) {
        return jwtService.verifyUserId(token, userid);
    }


    @GetMapping("/verifyopenid")
    public AuthResponse verifyopenid(String openid, String token) {
        return jwtService.verifyOpenid(token, openid);
    }


}
